<template>
  <div>
    <el-steps
      :active="maxReachedStep"
      align-center
      class="steps-container"
      :class="{ sticky: isSticky }"
    >
      <el-step
        v-for="(item2, index) in stagelist"
        :key="index"
        :title="item2.name"
        @click.native="handleStepClick(index)"
      ></el-step>
    </el-steps>

    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item
        :name="item.id"
        v-for="(item, index) in collapselist"
        :key="item.id"
        :id="`panel_${item.id}`"
      >
        <template #title>
          <div class="collapse-title">
            <span
              class="title-left"
              :class="{
                textcolor2: item.isCurrent,
                textcolor1: !item.isCurrent,
                'textcolor-yellow': duplicateCodes.includes(item.code),
              }"
              >{{ item.name }}</span
            >
            <span class="collapse-text">
              {{ activeNames.includes(item.id) ? "收起" : "展开" }}
            </span>
          </div>
        </template>
        <div
          class="collapse-box"
          v-if="item.code == 'create' && activeNames.includes(item.id)"
        >
          <CreateProject
            @get-stage="getStage"
            :currentStageid="currentStageid"
            :operation-list="operationList"
          ></CreateProject>
        </div>
        <div
          class="collapse-box"
          v-if="
            item.code == 'waitSelectionPricing' && activeNames.includes(item.id)
          "
        >
          <VerificationProject
            :currentStageid="currentStageid"
            @get-stage="getStage"
            :operation-list="operationList"
          ></VerificationProject>
        </div>
        <div
          class="collapse-box"
          v-if="
            item.code == 'waitSelectionFeedback' &&
            activeNames.includes(item.id)
          "
        >
          <FeedbackProject :currentStageid="currentStageid" :operation-list="operationList"></FeedbackProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'waitPackage' && activeNames.includes(item.id)"
        >
          <AllocationProject
            :operation-list="operationList"
            @get-stage="getStage"
            :currentStageid="currentStageid"
            :isremark="collapselist[index].remark"
          ></AllocationProject>
        </div>
        <div
          class="collapse-box"
          v-if="
            item.code == 'packageConfirming' && activeNames.includes(item.id)
          "
        >
          <ConpackageProject
            :operation-list="operationList"
            @get-stage="getStage"
            :currentStageid="currentStageid"
          ></ConpackageProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'contracting' && activeNames.includes(item.id)"
        >
          <ContractProject
            :operation-list="operationList"
            @get-stage="getStage"
            :currentStageid="currentStageid"
            @hand-drawer="handdrawer"
          ></ContractProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'signed' && activeNames.includes(item.id)"
        >
          <SignedProject
            :operation-list="operationList"
            :currentStageid="currentStageid"
            @get-stage="getStage"
          ></SignedProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'waitReceive' && activeNames.includes(item.id)"
        >
          <ReceivedProject
            :operation-list="operationList"
            :currentStageid="currentStageid"
            @get-stage="getStage"
          ></ReceivedProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'waitExecution' && activeNames.includes(item.id)"
        >
          <PendingexProject
            :operation-list="operationList"
            :currentStageid="currentStageid"
            @get-stage="getStage"
          ></PendingexProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'executing' && activeNames.includes(item.id)"
        >
          <ExecutionProject
            :operation-list="operationList"
            :currentStageid="currentStageid"
            @get-stage="getStage"
          ></ExecutionProject>
        </div>
        <div
          class="collapse-box"
          v-if="item.code == 'executed' && activeNames.includes(item.id)"
        >
          <AfterexProject
            :operation-list="operationList"
            :currentStageid="currentStageid"
          ></AfterexProject>
        </div>
      </el-collapse-item>
    </el-collapse>

    <div>
      <el-button @click="handdrawer" type="primary" class="certification">
        上传产品资质
      </el-button>
    </div>

    <el-drawer
      title="上传产品资质"
      :visible.sync="drawer"
      direction="rtl"
      size="50%"
      @close="drawerclose"
    >
      <ProjectQual
        :operation-list="operationList"
        :currentStageid="currentStageid"
      ></ProjectQual>
    </el-drawer>
  </div>
</template>

<script>
import CreateProject from "@/views/projectdetail/includes/CreateProject";
import VerificationProject from "@/views/projectdetail/includes/VerificationProject";
import FeedbackProject from "@/views/projectdetail/includes/FeedbackProject";
import AllocationProject from "@/views/projectdetail/includes/AllocationProject";
import ConpackageProject from "@/views/projectdetail/includes/ConpackageProject";
import ContractProject from "@/views/projectdetail/includes/ContractProject";
import SignedProject from "@/views/projectdetail/includes/SignedProject";
import ReceivedProject from "@/views/projectdetail/includes/ReceivedProject";
import PendingexProject from "@/views/projectdetail/includes/PendingexProject";
import ExecutionProject from "@/views/projectdetail/includes/ExecutionProject";
import AfterexProject from "@/views/projectdetail/includes/AfterexProject";
import ProjectQual from "@/views/projectdetail/create/ProjectQual";
import API from "@/api/apidetail";
export default {
  name: "ProjectDetail",
  components: {
    CreateProject,
    VerificationProject,
    FeedbackProject,
    AllocationProject,
    ConpackageProject,
    ContractProject,
    SignedProject,
    ReceivedProject,
    PendingexProject,
    ExecutionProject,
    AfterexProject,
    ProjectQual,
  },
  data() {
    return {
      isSticky: false, // 新增：控制是否吸顶
      stepsOffsetTop: 0, // 新增：步骤条初始距离顶部的距离
      stepsHeight: 0,
      maxReachedStep: 0,
      drawer: false,
      ismodal: true,
      operationList: [],
      activeNames: [],
      projectId: null,
      collapselist: [],
      currentStageid: null,
      active: 0,
      stagelist: [],
      originalStagelist: [
        { active: 0, code: "create", name: "创建中" },
        { active: 1, code: "waitSelectionPricing", name: "待选品核价" },
        { active: 2, code: "waitSelectionFeedback", name: "待选品反馈" },
        { active: 3, code: "waitPackage", name: "待配包" },
        { active: 4, code: "packageConfirming", name: "配包确认中" },
        { active: 5, code: "contracting", name: "合同中" },
        { active: 6, code: "signed", name: "已签单" },
        { active: 7, code: "waitReceive", name: "待收货" },
        { active: 8, code: "waitExecution", name: "待执行" },
        { active: 9, code: "executing", name: "执行中" },
        { active: 10, code: "executed", name: "执行完" },
      ],
      isremark: null,
    };
  },
  computed: {
    duplicateCodes() {
      // 统计每个code出现的次数
      const codeCount = this.collapselist.reduce((acc, item) => {
        acc[item.code] = (acc[item.code] || 0) + 1;
        return acc;
      }, {});
      // 筛选出出现次数 > 1 的code（重复的code）
      return Object.keys(codeCount).filter((code) => codeCount[code] > 1);
    },
  },
  methods: {
    handleChange(val) {
      console.log(val);
      //this.currentStageid = val[1];
      this.currentStageid = val[val.length - 1];
    },
    handdrawer() {
      this.drawer = true;
      this.ismodal = false;
    },
    //项目阶段
    getStage() {
      let id = this.$ls.get("projectId");
      let params = {
        projectId: this.projectId ? this.projectId : id,
      };

      API.getStage(params).then((res) => {
        if (res.key == 1000) {
          this.collapselist = res.result.list;
          this.activeNames = this.collapselist
            .filter((item) => item.isCurrent)
            .map((item) => item.id);
          const currentStage = this.collapselist.find((item) => item.isCurrent);
          this.currentStageid = currentStage.id;
          //this.isremark = currentStage.remark;
          if (currentStage) {
            // this.stagelist.forEach(item => {
            //   if(item.code == currentStage.code){
            //     this.active = item.active;
            //     // 初始化最大已到达步骤（关键：与当前阶段同步）
            //     this.maxReachedStep = item.active;
            //   }
            // });
            // 1. 将collapselist转换为步骤格式（仅保留必要字段）
            const collapsedStages = this.collapselist.map((item) => ({
              code: item.code,
              name: item.name,
            }));

            // 2. 找到当前进度在原始步骤中的位置
            const originalCurrent = this.originalStagelist.find(
              (item) => item.code == currentStage.code
            );
            const currentIndex = originalCurrent
              ? this.originalStagelist.indexOf(originalCurrent)
              : 0;

            // 3. 截取原始步骤中当前进度及之后的步骤
            const startIndex = currentIndex + 1;
            const remainingStages =
              startIndex < this.originalStagelist.length
                ? this.originalStagelist.slice(startIndex)
                : [];

            // 4. 生成新的stagelist：collapselist所有项 + 原始后续步骤
            this.stagelist = [...collapsedStages, ...remainingStages];

            // 5. 计算新的最大已到达步骤

            this.maxReachedStep = collapsedStages.length - 1;
          }
        }
      });
    },
    handleScroll() {
      // 获取当前滚动距离
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      // 当滚动距离超过步骤条初始位置时吸顶
      this.isSticky = scrollTop >= this.stepsOffsetTop;
    },
    getOperationList() {
      this.$store.state.permissionList.forEach((item) => {
        const [itemName] = item.permission.split(":");
        if (itemName === "project") {
            this.operationList = item.list.map(listItem => {
                return listItem.permission;
            });
        }
      });
      this.$store.state.permissionList.forEach((item) => {
        const [itemName] = item.permission.split(":");
        if (itemName === "order") {
            // this.operationList.push(
            //     item.list.map(listItem => {
            //       return listItem.permission;
            //   })
            // )

            this.operationList = [...this.operationList,...item.list.map(listItem => listItem.permission)]

        }
      });
      this.$store.state.permissionList.forEach((item) => {
        const [itemName] = item.permission.split(":");
        if (itemName === "shipment") {
            // this.operationList.push(
            //     item.list.map(listItem => {
            //       return listItem.permission;
            //   })
            // )

            this.operationList = [...this.operationList,...item.list.map(listItem => listItem.permission)]

        }
      });
      this.$store.state.permissionList.forEach(item => {
          const [itemName] = item.permission.split(":");
          if (itemName === "order") {
              this.operationList.push("order:view");
              item.list.some(listItem => {
                  const listItemType = listItem.permission.split(":")[1];
                  if (listItemType === "add") {
                      this.operationList.push("order:add");
                      return true;
                  }
                  if (listItemType === "submitFlagshipStoreData") {
                      this.operationList.push("order:submitFlagshipStoreData");
                      return true;
                  }
                  if (listItemType === "splitOrder") {
                      this.operationList.push("order:splitOrder");
                      return true;
                  }
                  return false;
              });
          }
      });
      console.log(this.operationList,"---------")
    },
    handleStepClick(index) {
      // 新增：如果点击的步骤在当前最大已到达步骤之后，则不生效
      if (index > this.maxReachedStep) {
        return;
      }

      const clickedStage = this.stagelist[index];
      if (!clickedStage) return;

      // 找到对应的折叠面板
      const targetPanel = this.collapselist.find(
        (item) => item.code == clickedStage.code
      );
      if (!targetPanel) {
        console.warn(`未找到 code 为 ${clickedStage.code} 的折叠面板`);
        return;
      }

      // 记录点击前的展开状态
      const wasExpanded = this.activeNames.includes(targetPanel.id);

      // 更新步骤激活状态
      this.active = index;
      if (index > this.maxReachedStep) {
        this.maxReachedStep = index;
      }

      // 处理折叠面板展开/收起
      if (wasExpanded) {
        // 已展开：收起（如果需要保留展开状态可删除此逻辑）
        // this.activeNames = this.activeNames.filter(id => id !== targetPanel.id);
      } else {
        // 未展开：展开
        this.activeNames = [...this.activeNames, targetPanel.id];
      }

      // 核心：无论展开/收起，只要是点击当前步骤就滚动（已展开时直接滚，未展开时等展开后滚）
      this.$nextTick(() => {
        // 获取锚点元素
        const anchorElement = document.getElementById(
          `panel_${targetPanel.id}`
        );
        if (anchorElement) {
          // 滚动到目标位置（平滑滚动）
          anchorElement.scrollIntoView({
            behavior: "smooth",
            block: "start", // 顶部对齐
          });
        }
      });
    },

    drawerclose() {
      this.ismodal = true;
    },
  },
  created() {},

  activated() {
    const id = this.$route.params.projectId;
    if (id) {
      this.$ls.set("projectId", id);
      this.projectId = id;
    }
    this.getStage();
    this.getOperationList();
  },
  mounted() {
    // 新增：获取步骤条初始位置和高度
    const stepsEl = document.querySelector(".steps-container");
    if (stepsEl) {
      const rect = stepsEl.getBoundingClientRect();
      this.stepsOffsetTop = rect.top + window.pageYOffset; // 初始距离顶部的绝对位置
      this.stepsHeight = rect.height; // 步骤条高度
    }

    // 新增：监听滚动事件
    window.addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    // 新增：移除滚动监听（避免内存泄漏）
    window.removeEventListener("scroll", this.handleScroll);
  },

  watch: {
    // $route() {
    //   // 每次路由进入当前页面都会执行
    //   if(this.$route.fullPath == '/ProjectDetail'){
    //     this.getStage();
    //   }
    // }
  },
};
</script>

<style>
.collapse-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.title-left {
  margin-left: 20px;
  font-size: large;
  font-weight: bold;
}

.collapse-text {
  font-size: 12px;
  cursor: pointer;
}

.collapse-box {
  padding: 0 8px;
}

.certification {
  position: fixed;
  bottom: 30%;
  right: 0;
  z-index: 999;
}

.steps-container {
  /* 给步骤条添加底部间距，避免吸顶时与内容紧贴 */
  margin-bottom: 20px;
  transition: all 0.3s ease; /* 平滑过渡效果 */
}

/* 吸顶状态样式 */
.steps-container.sticky {
  position: fixed;
  top: 65px;
  left: 233px;
  right: 2%;
  z-index: 998;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-collapse {
  transition: margin-top 0.3s ease;
}
.steps-container.sticky + .el-collapse {
  margin-top: calc(100px);
}

.textcolor1 {
  color: #0b57d0;
}

.textcolor2 {
  color: #303133;
}
.textcolor-yellow {
  color: #ffcc00;
}
</style>
